<template>
  <div style="display: flex">
    <el-container>
      <el-header>
        <div class="report_header" ref="headerHeight">
          <div class="report_header_left"></div>
          <div style="width: 300px;display: flex;align-items: center;margin-left: 10px;">
            <svg-icon class="primary" :icon-class="$route.meta.icon"/>
            <span style="margin-left: 5px;" class="primary">{{$route.meta.title}}</span>
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
            <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px">
              <div class="report_header_query">
                <queryCommunity @queryCommunityClick='queryCommunityClick' :shopname="query.communityName"></queryCommunity>              </div>
              <div class="report_header_query">
                <queryApartment @queryApartmentClick='queryApartmentClick' :shopname="query.buildingName" :communityId="query.communityId"></queryApartment>
              </div>
              <div class="report_header_query">
                <el-input prefix-icon="el-icon-search" placeholder="请输入公司名称" v-model="keyword" clearable></el-input>
<!--                <el-input prefix-icon="el-icon-search" placeholder="请输入企业名称"  v-model="query.name" clearable></el-input>-->
              </div>
            </div>
<!--            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="queryClick">查询</el-button>-->
<!--            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"-->
<!--                       v-permission="['company.add']">新增</el-button>-->
<!--            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="success" @click="importClick"-->
<!--                       v-permission="['building.add']">导入</el-button>-->

              <el-button style="margin-left: 10px;margin-top: 5px;"  size="small" type="primary" @click="queryClick">查询</el-button>
              <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"
              >新增</el-button>
              <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="success" @click="importClick"
              >导入</el-button>

          </div>
        </div>
      </el-header>
      <div class="pd10">

        <el-table
          :data="companyData"
          border
          stripe
          :height="curHeight"
          v-loadMore="[payLoads,'company-list-table']"
          ref="table"
          style="width: 100%;"
        >
          <el-table-column
            label="序号"
            type="index"
            width="50"
            align="center"
          >
          </el-table-column>
          <el-table-column label="公司名称" prop="name"></el-table-column>
          <el-table-column label="公司Logo" prop="name"></el-table-column>
          <el-table-column label="公司类型" prop="name"></el-table-column>

          <!--          <el-table-column label="企业ID" align="center" prop="id"width="80"></el-table-column>-->
          <el-table-column label="联系电话" align="center" prop="phone" width="80"></el-table-column>
          <el-table-column label="联系人" align="center" prop="linkman" width="80"></el-table-column>

          <el-table-column label="所属集团" align="center" prop="groupName" width="80"></el-table-column>
          <el-table-column label="所属账户" align="center" prop="companyName" min-width="100"></el-table-column>
          <el-table-column label="详情地址" align="center" prop="address"></el-table-column>
          <el-table-column
            label="是否绑定管理员"
            prop="mobile"
            width="120"
            align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.mobile == ''?'info':'success'">
                <span v-if="scope.row.mobile">{{scope.row.mobile}}</span>
                <span v-else>{{scope.row.mobile | watchBound}}</span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="状态"
            prop="status"
            width="100"
            align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status == 0?'warning':'success'">
                <span>{{scope.row.status | watchStatus}}</span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="审核说明" align="center" prop="address"></el-table-column>
          <el-table-column label="功能" fixed="right" width="200" align="center">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" style="margin-left: 10px"  @click="codeshowfunction(scope.row)">显示二维码</el-button>
              <el-tooltip v-permission="['company.audit']" class="item" effect="dark" content="审核" placement="top-start">
                 <el-button @click="openClick(scope.row)" :type="scope.row.status == 0? 'primary': 'success'" size="mini"
                 >{{scope.row.status == 0?'审核':'弃审'}}</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" fixed="right" width="80">
            <template slot-scope="scope">
              <div>
                <el-tooltip
                  v-permission="['company.edit']"
                  class="item"
                  effect="dark"
                  content="修改企业信息"
                  v-show="deleted == false"
                  placement="top-start"
                >
                  <a @click="editClick(scope.row)">
                    <i style="color: #409EFF" class="el-icon-edit"></i>
                  </a>
                </el-tooltip>
                <el-tooltip
                  v-permission="['company.del']"
                  class="item"
                  effect="dark"
                  content="删除企业"
                  v-show="deleted == false"
                  placement="top-start"
                >
                  <a style="margin-left: 10px" @click="deleteCompany(scope.row)">
                    <i style="color: #F56C6C" class="el-icon-delete"></i>
                  </a>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="pageNum"
          :limit.sync="pageSize"
          @pagination="loadCompany"
        ></pagination>
      </el-footer>
    </el-container>
    <el-dialog title="公司二维码" :visible.sync="codeShow" top="5vh" width="50%" :before-close="handleClose">
      <div style="width:100%;display: flex;justify-content: center;align-items: center;">
        <div ref="qrCodeDiv" class="qrCodeDiv" id="qrCodeDiv">
          <img :src="bindingImage" style="width: 100%;height: 100%;">
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<style scoped>
</style>

<script>
import permission from "@/directive/permission/index.js"; // 权限判断指令
import { list, del, update } from "@/api/order";
import { EventBus } from "@/api/eventBus";
import Pagination from "@/components/Pagination";
import loadMore from "@/utils/loadMore.js";
import utils from "@/utils/utils";
import queryApartment from '@/components/Query/queryGroup'
export default {
  name: "group-list",
  directives: { permission, loadMore },
  data() {
    return {
      bindingImage:'',
      companyData: [],
      pageNum: 1,
      pageSize: 20,
      total: 0,
      queryType: true,
      query: {
        communityId: this.$route.query.communityId,
        communityName:this.$route.query.communityName,
        buildingId: this.$route.query.buildingId ,
        buildingName:this.$route.query.buildingName,
      },
      keyword: "",
      curHeight: null,
      buildingName:this.$route.query.buildingName,
      buildingId:this.$route.query.buildingId,
      communityId:this.$route.query.communityId,
      communityName:this.$route.query.communityName,
      buildingForm:[],
      deleted: false,
      payLoads: "",
      companyOpenForm: {
        id: '',
        status: '',
      },
      codeShow:false
    };
  },
  components: {queryApartment,  Pagination},
  created() {
    var _this = this;
    _this.loadCompany();
    EventBus.$on("company-add", res => {
      _this.companyData.splice(0, 0, res);
    });
    EventBus.$on("company-edit", res => {
      for (var i = 0; i < _this.companyData.length; i++) {
        if (_this.companyData[i].id == res.id) {
          _this.companyData[i].name = res.name;
          _this.companyData[i].people = res.people;
          _this.companyData[i].status = res.status;
          _this.companyData[i].uesrId = res.userId;
          _this.companyData[i].mobile = res.mobile;
          _this.companyData[i].communityName = res.communityName;
          _this.companyData[i].communityId = res.communityId;
          _this.companyData[i].buildingId = res.buildingId;
          _this.companyData[i].buildingName = res.buildingName;
          _this.companyData[i].address = res.address;
        }
      }
    });
  },
  activated() {
    this.payLoads = new Date().getTime();
  },
  mounted() {
    this.comeIn();
    this.beforeMount();
  },
  filters: {
    formatDate: function(value) {
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      return y + "-" + MM + "-" + d;
    },
    watchStatus(val) {
      if (val == 1) {
        return '已认证'
      } else {
        return '未认证'
      }
    },
    watchBound(val) {
      if (val == 1) {
        return '未绑定'
      } else {
        return '未绑定'
      }
    },

  },
  methods: {
    handleClose() {
      this.codeShow = false;
    },
    downloadPictures() { // 保存二维码
      var oQrcode = document.querySelectorAll('.qrCodeDiv img')
      var url = oQrcode[0].src
      this.downloadIamge(url, '二维码')
    },
    downloadIamge (imgsrc, name) { // 下载图片地址和图片名
      var image = new Image()
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function () {
        var canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        var context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        var url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
        var a = document.createElement('a') // 生成一个a元素
        var event = new MouseEvent('click') // 创建一个单击事件
        a.download = name || 'photo' // 设置图片名称
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      }
      image.src = imgsrc
    },
    removeAllChild() {
      let qrCodeDiv = document.getElementById("qrCodeDiv");
      while(qrCodeDiv.hasChildNodes()) //当div下还存在子节点时 循环继续
      {
        qrCodeDiv.removeChild(qrCodeDiv.firstChild);
      }
    },
    codeshowfunction(item) {
      this.bindingImage = process.env.VUE_APP_BASE_API + '/zxing/createImage?data=http://fraud.rzico.com/2/' +item.id
      this.codeShow = true;
    },
    beforeMount() {
      window.onresize = () => {
        return (() => {
          if (this.queryType == false) {
            var h =
              document.documentElement.clientHeight ||
              document.body.clientHeight;
            this.curHeight = h - 266; //减去页面上固定高度height
          } else {
            var h =
              document.documentElement.clientHeight ||
              document.body.clientHeight;
            this.curHeight = h - 220; //减去页面上固定高度height
          }
        })();
      };
    },
    comeIn() {
      var h =
        document.documentElement.clientHeight || document.body.clientHeight;
      this.curHeight = h - 220; //减去页面上固定高度height
    },
    //编辑企业信息
    editClick(row) {
      this.$router.push({
        path: "/company/edit",
        query: { id: row.id }
      });
    },

    formatDate2Day(val) {
        if(val){
            let date = new Date(val);
            let y = date.getFullYear();
            let MM = date.getMonth() + 1;
            MM = MM < 10 ? "0" + MM : MM;
            let d = date.getDate();
            d = d < 10 ? "0" + d : d;
            return y + "-" + MM + "-" + d;
        }else{
            return ""
        }
    },
    formatDate2Time(val) {
        if(val){
            let date = new Date(val);
            let y = date.getFullYear();
            let MM = date.getMonth() + 1;
            MM = MM < 10 ? "0" + MM : MM;
            let d = date.getDate();
            d = d < 10 ? "0" + d : d;
            let h = date.getHours();
            h = h < 10 ? "0" + h : h;
            let m = date.getMinutes();
            m = m < 10 ? "0" + m : m;
            let s = date.getSeconds();
            s = s < 10 ? "0" + s : s;
            return y + "-" + MM + "-" + d + " " + h + ":" + m + ":" + s;
        }else{
            return ""
        }
    },
    //过滤企业列表
    formatList(data) {
      if (data.length > 0) {
        data.map(item => {
          item.createDate = this.formatDate2Day(item.createDate);
          item.modifyDate = this.formatDate2Time(item.modifyDate);
          item.rechangeDate = this.formatDate2Time(item.rechangeDate);
        });
      }
      return data;
    },
    loadCompany() {
      var _this = this;
      // console.log("keyword",_this.keyword,_this.keyword.name)
      let params = new URLSearchParams();
      params.append("pageNum", _this.pageNum);
      params.append("pageSize", _this.pageSize);
      params.append("keyword", _this.keyword);
      if(!utils.isNull(_this.communityId)){
        params.append("communityId", _this.communityId);
      }
      if(!utils.isNull(_this.buildingId)){
        params.append("buildingId", _this.buildingId);
      }

      params.append("deleted", _this.deleted);
      list(params).then(response => {
        console.info(response,1111)
        let list=response.data.data;
        _this.companyData = _this.formatList(list);
        _this.total = response.data.total;
        this.updateScroll();
        })
    },
    chooseClick() {
      this.queryType = !this.queryType;
      if (this.queryType == false) {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 266; //减去页面上固定高度height
      } else {
        var h =
          document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - 220; //减去页面上固定高度height
      }
    },
    addClick() {
      this.$router.push({
        path: "/company/add",
        query: {
          // communityId: this.communityId,
          communityName: this.communityName
        }
      });
    },
    importClick() {
      this.$router.push({
        path: "/company/import",
      });
    },
    deleteCompany(data) {
      console.log("data" + JSON.stringify(data));
      var _this = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          del(data.id)
            .then(response => {
              _this.companyData.forEach(function(item, index) {
                if (item.id === data.id) {
                  _this.companyData.splice(index, 1);
                }
              });
              _this.$message({
                message: response.content,
                offset: 120,
                center: true
              });
            })
            .catch(error => {
              console.log("error!!");
            });
        })
        .catch(() => {});
    },
    queryClick() {
      this.pageNum = 1;
      this.loadCompany();
    },
    queryApartmentClick(item){
      this.query.buildingId = item.shopId
      this.query.buildingName = item.name
      this.buildingId = this.query.buildingId
    },
    queryCommunityClick(item){
      this.query.communityId = item.shopId
      this.query.communityName = item.name
      this.communityId = this.query.communityId
    },
    resetClick() {
      this.query.communityId="";
      this.query.communityName="";
      this.query.buildingId="";
      this.query.buildingName="";
      this.keyword ="";
      this.pageNum = 1;
      this.loadCompany();
    },
    openClick(row) {
      var _this = this
      row.openLoading = true
      console.log(row,'row');
      this.companyOpenForm.id = row.id;
      if (row.status == 0) {
        this.companyOpenForm.status = 1
      } else if (row.status == 1) {
        this.companyOpenForm.status = 0
      }
      this.companyOpenForm.status = parseInt(this.companyOpenForm.status);
      update(_this.companyOpenForm).then(response => {
        console.log('companyOpenForm',response)
        _this.companyData.forEach(function (item) {
          if (item.id == row.id){
            item.status = response.data.status
          }
        })
        row.openLoading = false
        _this.$message({
          message: response.content,
          offset: 120,
          center: true
        });
      }).catch(error => {
        row.openLoading = false
        console.log('error!!')
      });
    },
    updateScroll() {
      window.sessionStorage.setItem("loadTopcompany-list-table", 0);
      window.sessionStorage.setItem("loadLeftcompany-list-table", 0);
    }
  }
};
</script>

<style scoped>
.el-footerBox {
  height: 50px !important;
  line-height: 50px !important;
  border-top: 1px solid #f2f2f2;
}
/deep/.el-header {
  padding: 10px;
  /* height: 100% !important; */
  padding-bottom: 0;
}
.report_header {
  width: 100%;
  min-height: 40px;
  box-sizing: border-box;
  background-color: rgba(248, 248, 248, 0.8);
  display: flex;
  align-items: center;
  padding-bottom: 5px;
  position: relative;
  padding-left: 5px;
  padding-right: 5px;
}
.report_header_left {
  width: 5px;
  height: 100%;
  background-color: #409EFF;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
}

.report_header_query {
  margin-left: 10px;
  width: 180px;
  margin-top: 5px;
}
</style>
